<?php

namespace app\teacher\controller;


use app\common\model\ClassesSignLog as ClassesSignLogModel;
use app\common\model\ClassesSign;
use app\common\model\UserBadge;
use think\Db;

class ClassesSignLog extends Base
{
    protected $model = null;
    public function __construct(ClassesSignLogModel $model)
    {
        parent::__construct();
        $this->model = $model;
    }


    /**
     * 列表
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $signId = $this->request->get('sign_id', 0);
        $type = $this->request->get('type', '');
        $status = $this->request->get('status', 0);
        if (!$signId) $this->error('参数错误');
        $this->success('获取成功', $this->model->list($signId, $type, $status, $page, $limit));
    }

    /**
     * 教师代签
     */
    public function teacher_sign_in()
    {
        $sign_log_id = $this->request->post('id', 0);
        if (!$sign_log_id) $this->error('参数错误');
        $type = $this->request->post('type', 1);
        $content = $this->request->post('content', '');
        $signLog = $this->model->where('id', $sign_log_id)->find();
        if (!$signLog) $this->error('数据不存在');
        $uid = $signLog['uid'];
        $sign = ClassesSign::where('id', $signLog['sign_id'])->find();
        $time = time();
        if ($sign['sign_end_time'] > $time) $this->error('签到未到截至时间');
        if ($signLog['status'] == 2) $this->error('学生已签到');
        $signLog->sign_type = 2;
        $signLog->status = 2;
        $signLog->type = $type;
        $signLog->content = $content;
        $signLog->teacher_uid = $this->uid();
        $res = $signLog->save();
        if ($res === false) $this->error('代签失败');
        $signCount = ClassesSign::where('classes_id', $sign['classes_id'])->where('sign_end_time', '<', $time)->count();
        $signLogCount = $this->model->where('classes_id', $sign['classes_id'])->where('uid', $uid)->where('status', 2)->count();
        if ($signCount == $signLogCount) UserBadge::where('user_id', $uid)->where('classes_id', $sign['classes_id'])->update(['state'=>1]);
        $this->success('代签成功');
    }

}